import requests
from PIL import Image
from pathlib import Path
from playwright.sync_api import sync_playwright


# 定义路径
png_path = Path("images")
gif_path = Path("images/wx.gif")
screenshots = []
# previous_label = None  # Track the last label to detect duplicates

def get_gif() -> None:
    global previous_label  # Make sure to use the global previous_label variable
    with sync_playwright() as playwright:  # 正确的使用 async_playwright
        browser = playwright.chromium.launch()
        context =  browser.new_context()
        page =   context.new_page()

        page.goto("http://www.nmc.cn/publish/radar/chinaall.html")

        labels = page.get_by_label("产品制作时间").inner_text()
        labels = labels.split("\n")  # 使用反转列表
        # latest_label=labels[-1]
        # labels=labels[:-1:3]
        # labels.append(latest_label)
        for index, label in enumerate(labels[:3], start=1):
            # if label == previous_label:
            #     continue

            page.get_by_label("产品制作时间").get_by_text(label).click()
            url = page.locator("#imgpath").get_attribute("src")
            url = url.split("?")[0]
            png_file_path = png_path / f"{index}.png"
            with open(png_file_path, "wb") as f:
                f.write(requests.get(url).content)
            # screenshots.append(png_file_path)
            # create_gif(screenshots)

            # previous_label = label  # Update the previous label with the current one
        
        context.close()
        browser.close()


def create_gif(screenshots: list):
    """
    Create a GIF from the provided list of screenshots.
    """
    images = []
    for screenshot in screenshots:
        # Use pathlib to check file existence and size
        if screenshot.exists() and screenshot.stat().st_size > 0:
            try:
                img = Image.open(screenshot)
                images.append(img)
            except Exception as e:
                print(f"Failed to open image {screenshot}: {e}")

    if images:
        images[0].save(
            gif_path,
            save_all=True,
            append_images=images[1:],
            duration=500,  # 500ms per frame
            loop=0         # Loop indefinitely
        )

if __name__ == '__main__':
    # main()
    get_gif()

